<template>
  <scroll-view class="whf" scroll-y>
    <view class="my wf y">
      <view class="header x jc" @click="goSetting">
        <view class="avatar xcc">
          <image v-if="me.other.avatar" :src="me.other.avatar" mode="aspectFill" fade-show class="whf" />
          <view v-else class="mac-ico-customer" />
          <text class="live">{{ me.live }}</text>
        </view>
        <view class="fg1 y pl1em info">
          <view class="name">{{ me.name }}</view>
          <!-- <view class="username">{{ me.username }}</view> -->
          <view class="money">余额: {{ me.moneys }}</view>
          <view class="groupname" v-if="merchant">{{ me._group?.name }}</view>
        </view>
        <view class="edit">点击编辑资料</view>
        <!-- <view class="mac-ico-d-r mr1em" /> -->
        <view class="my-bg">
          <image :src="mybg" mode="widthFix" />
        </view>
      </view>
      <view class="xw mt1em btns bot-common">
        <template v-if="merchant">
          <view class="y jc item mac-ico-business" @click="myShop"><text class="tabs">我的店铺</text></view>
          <view class="y jc item mac-ico-kucun" @click="goStock"><text class="tabs">库存</text></view>
          <view class="y jc item mac-ico-salesorder" @click="goOrder"><text class="tabs">订单</text></view>
          <view class="y jc item mac-ico-qr" @click="dpm"><text class="tabs">店铺二维码</text></view>
          <view class="y jc item mac-ico-qr" @click="tjm" v-if="me.live < 3"><text class="tabs">推荐码</text></view>
        </template>
        <view v-if="enablePrize" class="y jc item mac-ico-lingyongdan" @click="goPrize"><text class="tabs">奖品</text>
        </view>
      </view>
      <view class="types x jc za wf mt1em bot-common">
        <view class="tc qb" :class="!type ? 'active' : ''" @click="typeclick(0)">全部</view>
        <view class="tc dfk" :class="type == 1 ? 'active' : ''" @click="typeclick(1)">待付款</view>
        <view class="tc yfk" :class="type == 2 ? 'active' : ''" @click="typeclick(2)">已付款</view>
      </view>
      <view class="content y wf" v-if="!!data.length" :key="refresh">
        <view v-for="(i, ii) in data" class="line wf mt1em y" :key="ii">
          <template v-if="!!i.content.length">
            <GoodsItem v-for="(j, ji) in i.content" :key="ji" :modelValue="j._stock?._goods" :sum="abs(j.sum)" row
              class="wf" />
            <view class="sendDes" @click="clkSendDes(i.sendDes)" v-if="i.sendDes">
              发货信息:<text class="sendText ml1em">{{ i.sendDes }}</text>
              <view class="copy" @click="copyText(i.sendDes)">复制</view>
            </view>
            <view class="info mt04em"><text>{{ i._recvAddr }}</text></view>
            <view @click="scdj(i)" class="scdj" />
            <view class="btns wf zb x jc mt1em">
              <text class="zj pl04em">总价: ￥{{ (i.money / 100).toFixed(2) }}</text>
              <text class="pl04em">{{ i._t }}</text>
              <view class="x jc ">
                <button size="mini" v-if="i.recvTime === 0" @click="xgdz(i)" class="xgdz">修改地址</button>
                <button size="mini" type="warn" v-if="i.payTime == 0" @click="pay(i)" class="btnc pay">立即支付</button>
                <button size="mini" v-else-if="i.sendTime == 0" @click="lxkf(i)" class="lxkf">联系客服</button>
                <button size="mini" v-else-if="i.recvTime == 0" @click="qrsh(i)" class="qrsh">确认收货</button>
                <button size="mini" type="primary" v-if="i.payTime > 0 && !i.prize" @click="goLottery(i)"
                  class="btnc prize ml04em">立即抽奖</button>
              </view>
            </view>
          </template>
        </view>
      </view>
      <view v-else class="whf xcc non">没有记录,快去选购吧</view>
      <view v-if="refsh" class="whf xcc non">正在加载,请稍后</view>
    </view>
    <Dialog ref="dig" title="店铺二维码" titleClass="xcc">
      <view class="xcc whf">
        <image :src="url" mode="aspectFit" show-menu-by-longpress />
      </view>
    </Dialog>
  </scroll-view>
</template>
<script lang="ts">
  import { defineComponent } from "vue";
  import GoodsItem from "@/components/GoodsItem.vue";
  import { apiUrl, formatUrl, next, setMe } from "@/util";
  import Dialog from "@/components/Dialog.vue";
  export default defineComponent({
    name: "my",
    components: { GoodsItem, Dialog },
    data() {
      return {
        me: api.me,
        type: 0,
        data: [] as gt.sql.order[],
        current: 0,
        freshing: true,
        rules: [] as gt.Rules<gt.sql.order>,
        merchant: false,
        refsh: false,
        refresh: 0,
        url: "",
        /** 客服电话 */
        csPhone: "",
        enablePrize: 0,
      };
    },
    computed: {
      mybg() {
        return formatUrl("/static/my-bg.png", apiUrl);
      },
    },
    watch: {
      refresh() {
        this.me = api.me;
      },
    },
    async onShow() {
      await this.init();
      this.me = api.me;
    },
    onPullDownRefresh() {
      // uni.stopPullDownRefresh();
      this.onrefsh();
    },
    methods: {
      copyText(e: string) {
        uni.setClipboardData({
          data: e,
          success: () => {
            uni.showToast({ title: '复制成功', duration: 2000 });
          },
          fail: (res) => {
            console.log(res);
            uni.showToast({ title: '复制失败', icon: 'none', duration: 2000 });
          }
        });
      },
      async init() {
        uni.showLoading({ title: "正在加载,请稍后", mask: true });
        while (!api.mid) { await next(); }
        await setMe(await request({}, "user/me"));
        this.enablePrize = parseInt(await getSetting("enablePrize") || 0);
        this.merchant = api.me.gid != "2" && !!gd.group.getById(api.me.gid);
        const addroid = uni.getStorageSync("addroid");
        if (addroid) {
          uni.removeStorageSync("addroid");
          const addrid = uni.getStorageSync("addr");
          if (addrid) {
            uni.removeStorageSync("addr");
            const o = await gd.order.getById(addroid), a = await gd.addr.getById(addrid);
            if (o && a) {
              await api.request({ id: o.id, addr: a.id }, "order/addr");
              o.recvAddr = a;
              await format.order(o);
              this.refresh ^= 1;
            }
          }
        }
        await this.typeclick(0);
        uni.hideLoading();
      },
      abs(p?: number) {
        return Math.abs(p || 0);
      },
      onrefsh() {
        if (this.refsh) {
          return;
        }
        this.current = 0;
        this.fetch();
      },
      async fetch() {
        this.refsh = true;
        if (this.freshing) {
          const c = ++this.current,
            r = await gd.order.read(
              {
                "#page": { current: c, size: 10 },
                "#rule": this.rules,
                "#order": [["createTime", "DESC"]],
                showDel: 1,
              }
            ) as any as gt.PageData<gt.sql.order>;

          if (c > 1) {
            this.data.push(...r.data);
          } else {
            this.data = r.data;
          }
          this.freshing = this.data.length < r.total;
        }
        uni.stopPullDownRefresh();
        this.$nextTick(() => { this.refsh = false; });
        this.refresh ^= 1;
      },
      async typeclick(p: number) {
        const rules: gt.Rules<gt.sql.order> = [
          { field: "create", logic: "=", value: api.mid },
          { field: "cd", logic: "=", value: 0 },
        ];
        switch (p) {
          case 1: // 待付款
            rules.push({ field: "payTime", logic: "=", value: "0" });
            break;
          case 2: // 已付款
            rules.push({ field: "payTime", logic: ">", value: 0 });
            break;
          default:
            break;
        }
        this.type = p;
        this.rules = rules;
        this.current = 0;
        this.freshing = true;
        await this.fetch();
      },
      goSetting() {
        uni.navigateTo({ url: "/pages2/setting" });
      },
      async pay(p: gt.sql.order) {
        if (p && p.id && p.oid) {
          uni.requestPayment(Object.assign(await api.request({ id: p.id }, "wxpay"), {
            success(e: any) {
              console.log("支付成功", e);
            }, fail(e: any) {
              console.log("取消支付", e);
            }
          }));
        } else {
          msg({ title: "此单据无法支付,请重新下单", icon: "error" });
        }
      },
      goLottery(p: gt.sql.order) {
        uni.navigateTo({ url: "/pages3/lottery?id=" + p.id });
      },
      goStock() {
        uni.navigateTo({ url: "/pages2/stock" });
      },
      goOrder() {
        uni.navigateTo({ url: "/pages2/order" });
      },
      goPrize() {
        uni.navigateTo({ url: "/pages2/prize" });
      },
      async tjm() {
        this.url = format.url(`/tjm/${api.me.gid}`);
        (this.$refs.dig as any).open();
      },
      async dpm() {
        this.url = format.url(`/dpm/${api.me.gid}`);
        (this.$refs.dig as any).open();
      },
      myShop() {
        uni.setStorageSync("gid", api.me.gid);
        uni.reLaunch({ url: "/pages/index" });
      },
      async lxkf(_p: gt.sql.order) {
        if (!this.csPhone) {
          this.csPhone = await getSetting("csPhone");
        }
        uni.makePhoneCall({ phoneNumber: this.csPhone });
      },
      async qrsh(p: gt.sql.order) {
        await api.request({ id: p.id }, "order/recv");
        p.recvTime = parseInt(new Date().getTime() / 1000);
        this.refresh ^= 1;
      },
      clkSendDes(p: any) {
        if (p && typeof p === "string") {
          uni.setClipboardData({ data: p });
        }
      },
      async xgdz(p: gt.sql.order) {
        uni.setStorageSync("addroid", p.id);
        uni.navigateTo({ url: "/pages2/addr?back=" + p.id });
      },
      scdj(p: gt.sql.order) {
        uni.showModal({
          content: "删除后不可恢复;如未发货将返还所扣余额;是否继续?",
          showCancel: true,
          success: async (r) => {
            if (r && r.confirm) {
              await gd.order.deleteById(p.id);
              const i = this.data.findIndex(e => e.id == p.id);
              if (i >= 0) {
                this.data.splice(i, 1);
              }
            }
          },
        });
      }
    },
    // mounted() { },
  });
</script>
<style lang="scss" scoped>
  .my {
    position: relative;
    height: max-content;
    min-height: 100%;
    background-color: #F0F6F6;
    >.header {
      padding: 0 1em;
      align-items: flex-end;
      height: 10em;
      position: relative;
      >.avatar {
        position: relative;
        width: 4em;
        height: 4em;
        border-radius: .2em;
        background-color: #FFFFFF;
        border: 2px solid #FFFFFF;
        overflow: hidden;
        z-index: 9;
        position: absolute;
        bottom: -3em;
        >.live {
          position: absolute;
          bottom: 0;
          font-size: 0.6em;
          color: $uni-text-color-placeholder;
          background-color: #3333;
          border-radius: 100%;
        }
      }
      .mac-ico-customer {
        font-size: 2em;
      }
      .edit {
        position: absolute;
        right: 0;
        bottom: 2em;
        font-size: .8em;
        color: #FFFFFF;
        background-color: #ff9800;
        padding: 0 .5em;
        border-radius: 1em 0 0 1em;
        z-index: 9;
        padding: .2em .5em;
      }
      >.info {
        z-index: 9;
        position: absolute;
        bottom: -3em;
        left: 5em;
        .name {
          font-size: .9em;
        }
        >.money {
          color: $uni-color-error;
          font-size: .9em;
        }
      }
      .my-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 10em;
        z-index: 1;
        overflow: hidden;
        image {
          width: 100%;
        }
      }
    }
    >.btns {
      position: relative;
      flex-shrink: 0;
      margin: 4em 1em 0 1em;
      background-color: #FFFFFF;
      border-radius: .4em;
      padding: 0.4em 0;
      box-sizing: border-box;
      z-index: 9;
      >.item {
        width: 25%;
        margin: 0;
        padding: 0;
        border-radius: 0.4em;
        &::before {
          font-size: 1.3em;
          color: #ff9800;
        }
      }
    }
    >.content {
      padding: 0 1em;
      >.line {
        position: relative;
        >.scdj {
          color: $uni-color-error;
          position: absolute;
          top: .8rem;
          top: .8em;
          right: .5rem;
          &::before {
            content: "\e635";
          }
        }
        >.info {
          font-size: 0.8em;
          margin-left: 1em;
          color: $uni-text-color-placeholder;
        }
        >.sendDes {
          color: $uni-text-color-grey;
          margin-top: .5em;
          font-size: .8em;
          padding: 0 .2em;
          display: flex;
        }
        >.btns {
          position: relative;
          >.x {
            >button {
              margin: 0 1em .4em 0;
              padding: 0 0.4em;
            }
            >.xgdz {
              background-color: $uni-color-warning;
              color: $uni-text-color-inverse;
            }
            >.lxkf::before {
              content: "\e61a";
              margin-right: 1em;
              color: $uni-text-color-inverse;
            }
            >.lxkf {
              background-color: $uni-color-success;
            }
          }
          >.zj {
            color: $uni-color-error;
          }
        }
      }
    }
    >.types {
      >.tc {
        padding: .3em 2em;
      }
      >.active {
        // background-color: #00BCD4;
        color: #00BCD4;
        // border-bottom:1px solid #00BCD4;
        position: relative;
      }
      >.active::after {
        content: "";
        background: #00BCD4;
        position: absolute;
        bottom: 0;
        left: calc(50% - 1.5em);
        width: 3em;
        height: .2em;
        border-radius: .4em .4em 0 0;
      }
    }
    >.non {
      color: $uni-text-color-grey;
    }
  }
  .tabs {
    font-size: .7em;
    padding-top: .2em;
  }
</style>